{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 0
   },
   "source": [
    "# 线性回归的简洁实现\n",
    ":label:`sec_linear_concise`\n",
    "\n",
    "在过去的几年里，出于对深度学习强烈的兴趣，\n",
    "许多公司、学者和业余爱好者开发了各种成熟的开源框架。\n",
    "这些框架可以自动化基于梯度的学习算法中重复性的工作。\n",
    "在 :numref:`sec_linear_scratch`中，我们只运用了：\n",
    "（1）通过张量来进行数据存储和线性代数；\n",
    "（2）通过自动微分来计算梯度。\n",
    "实际上，由于数据迭代器、损失函数、优化器和神经网络层很常用，\n",
    "现代深度学习库也为我们实现了这些组件。\n",
    "\n",
    "在本节中，我们将介绍如何(**通过使用深度学习框架来简洁地实现**)\n",
    " :numref:`sec_linear_scratch`中的(**线性回归模型**)。\n",
    "\n",
    "## 生成数据集\n",
    "\n",
    "与 :numref:`sec_linear_scratch`中类似，我们首先[**生成数据集**]。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "origin_pos": 2,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: d2l in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (0.17.1)\n",
      "Requirement already satisfied: numpy==1.18.5 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from d2l) (1.18.5)\n",
      "Requirement already satisfied: jupyter==1.0.0 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from d2l) (1.0.0)\n",
      "Requirement already satisfied: matplotlib==3.3.3 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from d2l) (3.3.3)\n",
      "Requirement already satisfied: pandas==1.2.2 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from d2l) (1.2.2)\n",
      "Requirement already satisfied: requests==2.25.1 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from d2l) (2.25.1)\n",
      "Requirement already satisfied: jupyter-console in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from jupyter==1.0.0->d2l) (5.2.0)\n",
      "Requirement already satisfied: ipykernel in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from jupyter==1.0.0->d2l) (4.9.0)\n",
      "Requirement already satisfied: notebook in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from jupyter==1.0.0->d2l) (5.6.0)\n",
      "Requirement already satisfied: ipywidgets in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from jupyter==1.0.0->d2l) (7.4.1)\n",
      "Requirement already satisfied: qtconsole in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from jupyter==1.0.0->d2l) (4.4.1)\n",
      "Requirement already satisfied: nbconvert in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from jupyter==1.0.0->d2l) (5.4.0)\n",
      "Requirement already satisfied: cycler>=0.10 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from matplotlib==3.3.3->d2l) (0.10.0)\n",
      "Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.3 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from matplotlib==3.3.3->d2l) (3.0.6)\n",
      "Requirement already satisfied: kiwisolver>=1.0.1 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from matplotlib==3.3.3->d2l) (1.0.1)\n",
      "Requirement already satisfied: pillow>=6.2.0 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from matplotlib==3.3.3->d2l) (8.4.0)\n",
      "Requirement already satisfied: python-dateutil>=2.1 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from matplotlib==3.3.3->d2l) (2.7.3)\n",
      "Requirement already satisfied: pytz>=2017.3 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from pandas==1.2.2->d2l) (2018.5)\n",
      "Requirement already satisfied: urllib3<1.27,>=1.21.1 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from requests==2.25.1->d2l) (1.23)\n",
      "Requirement already satisfied: chardet<5,>=3.0.2 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from requests==2.25.1->d2l) (3.0.4)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from requests==2.25.1->d2l) (2021.10.8)\n",
      "Requirement already satisfied: idna<3,>=2.5 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from requests==2.25.1->d2l) (2.7)\n",
      "Requirement already satisfied: six in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from cycler>=0.10->matplotlib==3.3.3->d2l) (1.11.0)\n",
      "Requirement already satisfied: setuptools in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from kiwisolver>=1.0.1->matplotlib==3.3.3->d2l) (40.2.0)\n",
      "Requirement already satisfied: ipython>=4.0.0 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from ipykernel->jupyter==1.0.0->d2l) (6.5.0)\n",
      "Requirement already satisfied: traitlets>=4.1.0 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from ipykernel->jupyter==1.0.0->d2l) (4.3.2)\n",
      "Requirement already satisfied: jupyter_client in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from ipykernel->jupyter==1.0.0->d2l) (5.2.3)\n",
      "Requirement already satisfied: tornado>=4.0 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from ipykernel->jupyter==1.0.0->d2l) (5.1)\n",
      "Requirement already satisfied: nbformat>=4.2.0 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from ipywidgets->jupyter==1.0.0->d2l) (4.4.0)\n",
      "Requirement already satisfied: widgetsnbextension~=3.4.0 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from ipywidgets->jupyter==1.0.0->d2l) (3.4.1)\n",
      "Requirement already satisfied: pygments in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from jupyter-console->jupyter==1.0.0->d2l) (2.2.0)\n",
      "Requirement already satisfied: prompt-toolkit<2.0.0,>=1.0.0 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from jupyter-console->jupyter==1.0.0->d2l) (1.0.15)\n",
      "Requirement already satisfied: mistune>=0.8.1 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from nbconvert->jupyter==1.0.0->d2l) (0.8.3)\n",
      "Requirement already satisfied: jinja2 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from nbconvert->jupyter==1.0.0->d2l) (2.10)\n",
      "Requirement already satisfied: jupyter_core in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from nbconvert->jupyter==1.0.0->d2l) (4.4.0)\n",
      "Requirement already satisfied: entrypoints>=0.2.2 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from nbconvert->jupyter==1.0.0->d2l) (0.2.3)\n",
      "Requirement already satisfied: bleach in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from nbconvert->jupyter==1.0.0->d2l) (2.1.4)\n",
      "Requirement already satisfied: pandocfilters>=1.4.1 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from nbconvert->jupyter==1.0.0->d2l) (1.4.2)\n",
      "Requirement already satisfied: testpath in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from nbconvert->jupyter==1.0.0->d2l) (0.3.1)\n",
      "Requirement already satisfied: defusedxml in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from nbconvert->jupyter==1.0.0->d2l) (0.5.0)\n",
      "Requirement already satisfied: prometheus-client in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from notebook->jupyter==1.0.0->d2l) (0.3.1)\n",
      "Requirement already satisfied: terminado>=0.8.1 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from notebook->jupyter==1.0.0->d2l) (0.8.1)\n",
      "Requirement already satisfied: Send2Trash in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from notebook->jupyter==1.0.0->d2l) (1.5.0)\n",
      "Requirement already satisfied: pyzmq>=17 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from notebook->jupyter==1.0.0->d2l) (17.1.2)\n",
      "Requirement already satisfied: ipython-genutils in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from notebook->jupyter==1.0.0->d2l) (0.2.0)\n",
      "Requirement already satisfied: jedi>=0.10 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from ipython>=4.0.0->ipykernel->jupyter==1.0.0->d2l) (0.12.1)\n",
      "Requirement already satisfied: decorator in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from ipython>=4.0.0->ipykernel->jupyter==1.0.0->d2l) (4.3.0)\n",
      "Requirement already satisfied: simplegeneric>0.8 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from ipython>=4.0.0->ipykernel->jupyter==1.0.0->d2l) (0.8.1)\n",
      "Requirement already satisfied: appnope in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from ipython>=4.0.0->ipykernel->jupyter==1.0.0->d2l) (0.1.0)\n",
      "Requirement already satisfied: backcall in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from ipython>=4.0.0->ipykernel->jupyter==1.0.0->d2l) (0.1.0)\n",
      "Requirement already satisfied: pickleshare in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from ipython>=4.0.0->ipykernel->jupyter==1.0.0->d2l) (0.7.4)\n",
      "Requirement already satisfied: pexpect in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from ipython>=4.0.0->ipykernel->jupyter==1.0.0->d2l) (4.6.0)\n",
      "Requirement already satisfied: jsonschema!=2.5.0,>=2.4 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from nbformat>=4.2.0->ipywidgets->jupyter==1.0.0->d2l) (2.6.0)\n",
      "Requirement already satisfied: wcwidth in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from prompt-toolkit<2.0.0,>=1.0.0->jupyter-console->jupyter==1.0.0->d2l) (0.1.7)\n",
      "Requirement already satisfied: html5lib!=1.0b1,!=1.0b2,!=1.0b3,!=1.0b4,!=1.0b5,!=1.0b6,!=1.0b7,!=1.0b8,>=0.99999999pre in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from bleach->nbconvert->jupyter==1.0.0->d2l) (1.0.1)\n",
      "Requirement already satisfied: MarkupSafe>=0.23 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from jinja2->nbconvert->jupyter==1.0.0->d2l) (1.0)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: webencodings in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from html5lib!=1.0b1,!=1.0b2,!=1.0b3,!=1.0b4,!=1.0b5,!=1.0b6,!=1.0b7,!=1.0b8,>=0.99999999pre->bleach->nbconvert->jupyter==1.0.0->d2l) (0.5.1)\r\n",
      "Requirement already satisfied: parso>=0.3.0 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from jedi>=0.10->ipython>=4.0.0->ipykernel->jupyter==1.0.0->d2l) (0.3.1)\r\n",
      "Requirement already satisfied: ptyprocess>=0.5 in /Users/wangjiaqi/anaconda3/lib/python3.7/site-packages (from pexpect->ipython>=4.0.0->ipykernel->jupyter==1.0.0->d2l) (0.6.0)\r\n"
     ]
    },
    {
     "ename": "ModuleNotFoundError",
     "evalue": "No module named 'torchvision'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mModuleNotFoundError\u001b[0m                       Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-1-68458b660b05>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m      3\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mtorch\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      4\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0mtorch\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mutils\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mdata\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0;32mfrom\u001b[0m \u001b[0md2l\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mtorch\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0md2l\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;32m~/anaconda3/lib/python3.7/site-packages/d2l/torch.py\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m     22\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mnumpy\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     23\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mtorch\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 24\u001b[0;31m \u001b[0;32mimport\u001b[0m \u001b[0mtorchvision\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     25\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0mPIL\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mImage\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     26\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0mtorch\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mnn\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'torchvision'"
     ]
    }
   ],
   "source": [
    "!pip install d2l\n",
    "import numpy as np\n",
    "import torch\n",
    "from torch.utils import data \n",
    "from d2l import torch as d2l"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "origin_pos": 4,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "true_w = torch.tensor([2, -3.4]) #真实权重\n",
    "true_b = 4.2 #真实偏差\n",
    "features, labels = d2l.synthetic_data(true_w, true_b, 1000) #应用liner-regression-concise里面的函数，生成训练数据"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 5
   },
   "source": [
    "## 读取数据集\n",
    "\n",
    "我们可以[**调用框架中现有的API来读取数据**]。\n",
    "我们将`features`和`labels`作为API的参数传递，并通过数据迭代器指定`batch_size`。\n",
    "此外，布尔值`is_train`表示是否希望数据迭代器对象在每个迭代周期内打乱数据。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "origin_pos": 7,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "def load_array(data_arrays, batch_size, is_train=True):  #@save\n",
    "    \"\"\"\n",
    "    构造一个PyTorch数据迭代器\n",
    "    @para data_arrays 训练数据\n",
    "    @para batch_size 批量大小\n",
    "    @para is_train=True 是否训练，选择True会随机选择数据\n",
    "    @return\n",
    "        迭代器，每次返回batch_size大小的两组数据，一个是训练样本，一个是对应的标签 \n",
    "    \"\"\"\n",
    "    dataset = data.TensorDataset(*data_arrays) #数据集\n",
    "    return data.DataLoader(dataset, batch_size, shuffle=is_train) # dataloader可以理解为数据的一个接口，说明见https://blog.csdn.net/lipengfei0427/article/details/109547241"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "origin_pos": 9,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "batch_size = 10 #批量大小\n",
    "data_iter = load_array((features, labels), batch_size) #随机返回的数据"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 10
   },
   "source": [
    "使用`data_iter`的方式与我们在 :numref:`sec_linear_scratch`中使用`data_iter`函数的方式相同。为了验证是否正常工作，让我们读取并打印第一个小批量样本。\n",
    "与 :numref:`sec_linear_scratch`不同，这里我们使用`iter`构造Python迭代器，并使用`next`从迭代器中获取第一项。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "origin_pos": 11,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "next(iter(data_iter))# iter构造Python迭代器，并使用next从迭代器中获取第一项。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 12
   },
   "source": [
    "## 定义模型\n",
    "\n",
    "当我们在 :numref:`sec_linear_scratch`中实现线性回归时，\n",
    "我们明确定义了模型参数变量，并编写了计算的代码，这样通过基本的线性代数运算得到输出。\n",
    "但是，如果模型变得更加复杂，且当你几乎每天都需要实现模型时，你会想简化这个过程。\n",
    "这种情况类似于为自己的博客从零开始编写网页。\n",
    "做一两次是有益的，但如果每个新博客你就花一个月的时间重新开始编写网页，那并不高效。\n",
    "\n",
    "对于标准深度学习模型，我们可以[**使用框架的预定义好的层**]。这使我们只需关注使用哪些层来构造模型，而不必关注层的实现细节。\n",
    "我们首先定义一个模型变量`net`，它是一个`Sequential`类的实例。\n",
    "`Sequential`类将多个层串联在一起。\n",
    "当给定输入数据时，`Sequential`实例将数据传入到第一层，\n",
    "然后将第一层的输出作为第二层的输入，以此类推。\n",
    "在下面的例子中，我们的模型只包含一个层，因此实际上不需要`Sequential`。\n",
    "但是由于以后几乎所有的模型都是多层的，在这里使用`Sequential`会让你熟悉“标准的流水线”。\n",
    "\n",
    "回顾 :numref:`fig_single_neuron`中的单层网络架构，\n",
    "这一单层被称为*全连接层*（fully-connected layer），\n",
    "因为它的每一个输入都通过矩阵-向量乘法得到它的每个输出。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 14,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "在PyTorch中，全连接层在`Linear`类中定义。\n",
    "值得注意的是，我们将两个参数传递到`nn.Linear`中。\n",
    "第一个指定输入特征形状，即2，第二个指定输出特征形状，输出特征形状为单个标量，因此为1。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "origin_pos": 17,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "# nn是神经网络的缩写\n",
    "from torch import nn\n",
    "\n",
    "# Sequential一个容器，list of layers\n",
    "net = nn.Sequential(nn.Linear(2, 1)) #nn.Linear为线性层函数，输入的纬度2；输出的纬度1，"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 19
   },
   "source": [
    "## (**初始化模型参数**)\n",
    "\n",
    "在使用`net`之前，我们需要初始化模型参数。\n",
    "如在线性回归模型中的权重和偏置。\n",
    "深度学习框架通常有预定义的方法来初始化参数。\n",
    "在这里，我们指定每个权重参数应该从均值为0、标准差为0.01的正态分布中随机采样，\n",
    "偏置参数将初始化为零。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 21,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "正如我们在构造`nn.Linear`时指定输入和输出尺寸一样，\n",
    "现在我们能直接访问参数以设定它们的初始值。\n",
    "我们通过`net[0]`选择网络中的第一个图层，\n",
    "然后使用`weight.data`和`bias.data`方法访问参数。\n",
    "我们还可以使用替换方法`normal_`和`fill_`来重写参数值。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "origin_pos": 24,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "net[0].weight.data.normal_(0, 0.01) #权重初始化，用normal方式\n",
    "net[0].bias.data.fill_(0) #初始化偏差为0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 27,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 29
   },
   "source": [
    "## 定义损失函数\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 31,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "[**计算均方误差使用的是`MSELoss`类，也称为平方$L_2$范数**]。\n",
    "默认情况下，它返回所有样本损失的平均值。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "origin_pos": 34,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "loss = nn.MSELoss() #均方误差函数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 36
   },
   "source": [
    "## 定义优化算法\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 38,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "小批量随机梯度下降算法是一种优化神经网络的标准工具，\n",
    "PyTorch在`optim`模块中实现了该算法的许多变种。\n",
    "当我们(**实例化一个`SGD`实例**)时，我们要指定优化的参数\n",
    "（可通过`net.parameters()`从我们的模型中获得）以及优化算法所需的超参数字典。\n",
    "小批量随机梯度下降只需要设置`lr`值，这里设置为0.03。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "origin_pos": 41,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "trainer = torch.optim.SGD(net.parameters(), lr=0.03) #随机梯度下降优化算法SGD，传入模型的参数，学习率lr"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 43
   },
   "source": [
    "## 训练\n",
    "\n",
    "通过深度学习框架的高级API来实现我们的模型只需要相对较少的代码。\n",
    "我们不必单独分配参数、不必定义我们的损失函数，也不必手动实现小批量随机梯度下降。\n",
    "当我们需要更复杂的模型时，高级API的优势将大大增加。\n",
    "当我们有了所有的基本组件，[**训练过程代码与我们从零开始实现时所做的非常相似**]。\n",
    "\n",
    "回顾一下：在每个迭代周期里，我们将完整遍历一次数据集（`train_data`），\n",
    "不停地从中获取一个小批量的输入和相应的标签。\n",
    "对于每一个小批量，我们会进行以下步骤:\n",
    "\n",
    "* 通过调用`net(X)`生成预测并计算损失`l`（前向传播）。\n",
    "* 通过进行反向传播来计算梯度。\n",
    "* 通过调用优化器来更新模型参数。\n",
    "\n",
    "为了更好的衡量训练效果，我们计算每个迭代周期后的损失，并打印它来监控训练过程。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "origin_pos": 45,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "num_epochs = 3 #迭代周期为3\n",
    "for epoch in range(num_epochs):\n",
    "    for X, y in data_iter:  #返回batch_size大小的数据\n",
    "        l = loss(net(X) ,y) #计算损失函数\n",
    "        trainer.zero_grad() #梯度清零\n",
    "        l.backward() #计算梯度\n",
    "        trainer.step() #更新参数\n",
    "    l = loss(net(features), labels) #计算所有样本的loss\n",
    "    print(f'epoch {epoch + 1}, loss {l:f}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 47
   },
   "source": [
    "下面我们[**比较生成数据集的真实参数和通过有限数据训练获得的模型参数**]。\n",
    "要访问参数，我们首先从`net`访问所需的层，然后读取该层的权重和偏置。\n",
    "正如在从零开始实现中一样，我们估计得到的参数与生成数据的真实参数非常接近。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "origin_pos": 49,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "w = net[0].weight.data\n",
    "print('w的估计误差：', true_w - w.reshape(true_w.shape))\n",
    "b = net[0].bias.data\n",
    "print('b的估计误差：', true_b - b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 51
   },
   "source": [
    "## 小结\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 53,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "* 我们可以使用PyTorch的高级API更简洁地实现模型。\n",
    "* 在PyTorch中，`data`模块提供了数据处理工具，`nn`模块定义了大量的神经网络层和常见损失函数。\n",
    "* 我们可以通过`_`结尾的方法将参数替换，从而初始化参数。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 55
   },
   "source": [
    "## 练习\n",
    "\n",
    "1. 如果将小批量的总损失替换为小批量损失的平均值，你需要如何更改学习率？\n",
    "1. 查看深度学习框架文档，它们提供了哪些损失函数和初始化方法？用Huber损失代替原损失，即\n",
    "    $$l(y,y') = \\begin{cases}|y-y'| -\\frac{\\sigma}{2} & \\text{ if } |y-y'| > \\sigma \\\\ \\frac{1}{2 \\sigma} (y-y')^2 & \\text{ 其它情况}\\end{cases}$$\n",
    "1. 你如何访问线性回归的梯度？\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 57,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "[Discussions](https://discuss.d2l.ai/t/1781)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
